import KoaRouter from 'koa-router';

import AuthMiddleware from '../middleware/authMiddleware';
import fs from 'fs';
import path from 'path';
import { replace } from 'lodash-es';
import { log } from '../logger';

const apiRouter = new KoaRouter({ prefix: '/api/v1' });

apiRouter.use(async ({ req }, next) => {
  const start = Date.now();
  // 临时记录一下服务运行时占用的内存情况
  const MU = (process.memoryUsage().heapUsed / (1024 * 1024)).toFixed(2) + 'MB';
  await next();
  const ms = Date.now() - start;
  console.log('内存使用信息:', MU, `请求的连接：${req.method} ${req.url} - ${ms}ms`);
  log.info(`内存使用信息: ${MU}`, `请求的连接：${req.method} ${req.url} 执行时长: ${ms}ms`);
});

apiRouter.use(AuthMiddleware);
apiRouter.get('/', async (ctx, next) => {
  ctx.body = '访问成功';
  await next();
});

// 封装递归
function loadRoutes(filePath: string) {
  //将当前目录下 都读出来
  const files = fs.readdirSync(filePath);
  // 过滤
  files
    .filter((file) => {
      //读取的时候会将当前目录的 index.js 也读取出来，这个不需要，如果拿到别的地方可以不加这个判断
      if (filePath !== __dirname && file === 'index.ts') {
        console.log("routes module must not be 'index.ts' ");
      }
      return file !== 'index.ts';
    })
    .forEach(async (file) => {
      const newFilePath = path.join(filePath, file);
      // 是目录
      if (fs.statSync(newFilePath).isDirectory()) {
        loadRoutes(newFilePath); // 递归
      } else {
        // 方式三：使用import() 和 export default router, 每个routes文件就需要使用 export default router 导出
        const currentDirectory = __dirname;
        const relativePath = path.relative(currentDirectory, newFilePath);
        const res = await import('./' + replace(relativePath, '.ts', ''));
        apiRouter.use(res.default.routes());
        apiRouter.use(res.default.allowedMethods());
      }
    });
}

//启动
loadRoutes(__dirname);

export default apiRouter;
